package com.twq.collection.framework.view

/**
 * Created by tangweiqun on 2017/12/10.
 */
object ViewsTest {
  def main(args: Array[String]): Unit = {
    //view 的作用
    val v = Vector(1 to 10: _*)
    val result1 = v.map(_ + 1) // strict
    val result2 = result1.map(_ * 2)

    val vv = v.view
    val result3 = vv.map(_ + 1) // non-strict(lazy)
    val result4 = result3.map(_ * 2)
    result4.force


    //view的两个使用场景
    //1、消除中间结果，提升性能
    def isPalindrome(x: String) = x == x.reverse

    def findPalindrome(s: Seq[String]) = s find isPalindrome

    val words = Seq("test", "tttt", "man", "sd", "444", "45", "", "")
    findPalindrome(words take 100000) //会产生中间结果
    findPalindrome(words.view take 100000) //不会产生中间结构

    //2、view和可变集合的配合
    val arr = (0 to 9).toArray
    val subarr = arr.view.slice(3, 6)

    def negate(xs: collection.mutable.Seq[Int]) =
      for (i <- 0 until xs.length) xs(i) = -xs(i)

    negate(subarr)
    arr //部分元素被修改了

    //对于数据量比较少的集合的操作，建议使用strict模式，而不要采用view的模式
    //因为对于数据量少的集合使用view的开销可能还比产生中间结果的要大

  }
}
